package lan.agents;

import java.io.IOException;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import jade.content.onto.basic.Result;
import jade.core.Agent;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import jade.util.leap.ArrayList;
import jade.util.leap.List;
import vnu.ACLMessageX;

import vnu.JobAgent;
import vnu.Record;
import vocabulary.MyDatabaseVoca;
import vocabulary.MyMapVoca;

public class DBAgent extends JobAgent implements MyDatabaseVoca, MyMapVoca {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
		 ArrayList newsList;
	 
	 protected void setup(){
		 super.setup();
		 newsList = new ArrayList();
		 // khoi tao goi 4 tin moi nhat
		 addBehaviour(new ReceiveMsg(this));
		 
	 }

//--------------
	 


	 class ReceiveMsg extends CyclicBehaviour{
		 private Connection dbconection;
		
		 /**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		/**
		 * 
		 */
		
		public ReceiveMsg(Agent a){
			super(a);
		}
		public void action(){
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				try {
					dbconection = DriverManager.getConnection(URL, MYSQL_USER,
							MYSQL_PASSWORD);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		//-----------------------------------------------------process received message..................... 
			 ACLMessage receivedMsg = receive();
			 if(receivedMsg == null){
				 block();
				 return;
			 }
			 if(receivedMsg.getSender().getLocalName().equals(AGENT_MANAGER) ){
			 try {
				ACLMessageX content = (ACLMessageX)receivedMsg.getContentObject();
				int performative = content.getPerformative();
				switch (performative) {
				case ACLMessage.REQUEST:{
					System.out.println("[DBagent] request from " + content.getSource());
					if( content.getContent().equalsIgnoreCase(HOME)){
					setNew(MYSQL_TABLE, HOME, NUMBEROFROWS);
				
					}
					else if( content.getContent().equalsIgnoreCase(BACK)){
						
						setNew(MYSQL_TABLE, BACK, NUMBEROFROWS);
					}
					else{
						setNew(MYSQL_TABLE, NEXT, NUMBEROFROWS);
						
					}
					
					addBehaviour(new HandleMsg(myAgent,receivedMsg));
					
				}
					
					break;

				default:
				
					break;
				}
			} catch (UnreadableException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			 }
			 
		
			 
		 }
	
		private	 void setNew(String tableName,String request,int numberofRows){
			 

			 if(request.equalsIgnoreCase(HOME)){
			 try {
				 
				Statement statement = dbconection.createStatement();
				String statementQuery = "Select * from " + tableName + " order by id DESC limit " + numberofRows;
				ResultSet resultSet = statement.executeQuery(statementQuery);
				Record news;
				while(resultSet.next()){
					news = new Record(resultSet.getInt(1), resultSet.getInt(2), resultSet.getString(3), resultSet.getString(4), 
							resultSet.getString(5), resultSet.getInt(6), resultSet.getString(7),resultSet.getString(8),
							resultSet.getString(9), resultSet.getString(10), resultSet.getString(11), resultSet.getString(12));
					newsList.add(news);
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			 
			 }
			 else if(request.equalsIgnoreCase(NEXT)){
				 Record temp = (Record)newsList.get(newsList.size()-1);
				 System.out.println(temp.getId());
				 int index = temp.getId()-1;
				 int end = index - numberofRows;
			
				 try {
					Statement statement = dbconection.createStatement();
					String statementQuery = "Select * from " + tableName + " where id <= "+ index  + " order by id DESC limit " + numberofRows;
					
					ResultSet resultSet = statement.executeQuery(statementQuery);
					Record news;
					newsList.clear();
					while(resultSet.next()){
						news = new Record(resultSet.getInt(1), resultSet.getInt(2), resultSet.getString(3), resultSet.getString(4), 
								resultSet.getString(5), resultSet.getInt(6), resultSet.getString(7),resultSet.getString(8),
								resultSet.getString(9), resultSet.getString(10), resultSet.getString(11), resultSet.getString(12));
						newsList.add(news);
					}
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
					
			 }
			 
			 else if(request.equalsIgnoreCase(BACK)){
				 
				 Record temp = (Record)newsList.get(newsList.size()-1);
				 int index = temp.getId()+1;
				 int end = index + numberofRows;
				 
				 try {
						Statement statement = dbconection.createStatement();
						String statementQuery = "Select * from " + tableName + " where id  between "+ index  + " and " + end;
						
						ResultSet resultSet = statement.executeQuery(statementQuery);
						
						// neu newList khong la cac tin moi nhat thi cap nhat lai
						if(resultSet.first()){
						Record news;
						newsList.clear();
						while(resultSet.next()){
							news = new Record(resultSet.getInt(1), resultSet.getInt(2), resultSet.getString(3), resultSet.getString(4), 
									resultSet.getString(5), resultSet.getInt(6), resultSet.getString(7),resultSet.getString(8),
									resultSet.getString(9), resultSet.getString(10), resultSet.getString(11), resultSet.getString(12));
							newsList.add(news);
						}
						}
						
						
					} catch (SQLException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				 
				 
			 }
			 else return;
		 }
	
	 
	 }


class HandleMsg extends OneShotBehaviour{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	 
	private ACLMessage request;
	public HandleMsg(Agent a, ACLMessage receive){
		super(a);
		this.request=receive;
		
	}
	@Override
	public void action() {
		// TODO Auto-generated method stub
		
		try {
			
	
			ACLMessage reply =  new ACLMessage();
			ACLMessageX content = (ACLMessageX) request.getContentObject();
			
			reply.addReceiver(content.getSource());
		
			
			reply.setPerformative(ACLMessage.INFORM);
	
			reply.setContentObject((Serializable)newsList);
			send(reply);
			System.out.println("sending the result....");
		} catch (IOException | UnreadableException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	
	
 }
}
